package com.bckj.fastboot.core.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class BeanAccessorProvider {

    private static final ConcurrentMap<Class<?>, BeanAccessor<?>> cache = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    public static <T> BeanAccessor<T> get(Class<T> beanClass) {
        BeanAccessor<?> accessor = cache.computeIfAbsent(beanClass, t -> {
            try {
                return new BeanAccessor<>(beanClass);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return (BeanAccessor<T>)accessor;
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Object> getAllValues(Object bean) {
        Class<?> type = bean.getClass();
        BeanAccessor<?> accessor = cache.computeIfAbsent(type, t -> {
            try {
                return new BeanAccessor<>(type);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return ((BeanAccessor<Object>)accessor).getAllValues(bean);
    }
}
